package com.cyan.note.service.impl;

import com.cyan.note.dto.admin.ManagerCreateRequest;
import com.cyan.note.dto.admin.ManagerResponse;
import com.cyan.note.dto.admin.ManagerUpdateRequest;
import com.cyan.note.entity.Shop;
import com.cyan.note.entity.User;
import com.cyan.note.mapper.ShopMapper;
import com.cyan.note.mapper.UserMapper;
import com.cyan.note.service.AdminManagerService;
import com.cyan.note.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 超级管理员-店长管理服务实现类
 * 严格遵循数据隔离原则 - 只能管理店长账户的系统信息
 * 
 * @author ZhangzhenYu
 * @since 2025-01-14
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AdminManagerServiceImpl implements AdminManagerService {

    private final UserMapper userMapper;
    private final ShopMapper shopMapper;
    private final PasswordEncoder passwordEncoder;

    /**
     * 有效的用户状态
     */
    private static final List<String> VALID_STATUSES = Arrays.asList("active", "inactive", "locked");

    @Override
    public List<ManagerResponse> getAllManagers() {
        log.info("超级管理员查询所有店长账户列表");
        List<User> managers = userMapper.selectAllManagers();
        return managers.stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
    }

    @Override
    public List<ManagerResponse> getManagersByShopId(Long shopId) {
        log.info("超级管理员按店铺查询店长账户, shopId: {}", shopId);
        
        if (shopId == null || shopId <= 0) {
            throw new IllegalArgumentException("无效的店铺ID");
        }
        
        // 验证店铺是否存在
        Shop shop = shopMapper.selectById(shopId);
        if (shop == null) {
            throw new RuntimeException("店铺不存在");
        }
        
        List<User> managers = userMapper.selectManagersByShopId(shopId);
        return managers.stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
    }

    @Override
    public List<ManagerResponse> getManagersByStatus(String status) {
        log.info("超级管理员按状态查询店长账户, status: {}", status);
        
        if (!VALID_STATUSES.contains(status)) {
            throw new IllegalArgumentException("无效的账户状态: " + status);
        }
        
        List<User> managers = userMapper.selectManagersByStatus(status);
        return managers.stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
    }

    @Override
    public ManagerResponse getManagerById(Long id) {
        log.info("超级管理员查询店长账户详情, managerId: {}", id);
        
        if (id == null || id <= 0) {
            throw new IllegalArgumentException("无效的用户ID");
        }
        
        User user = userMapper.selectById(id);
        if (user == null || !"manager".equals(user.getRole())) {
            throw new RuntimeException("店长账户不存在");
        }
        
        return convertToResponse(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ManagerResponse createManager(ManagerCreateRequest request) {
        log.info("超级管理员创建店长账户, username: {}, shopId: {}", request.getUsername(), request.getShopId());
        
        // 1. 验证用户名是否已存在
        if (isUsernameExists(request.getUsername())) {
            throw new RuntimeException("用户名已存在: " + request.getUsername());
        }
        
        // 2. 验证店铺是否存在
        Shop shop = shopMapper.selectById(request.getShopId());
        if (shop == null) {
            throw new RuntimeException("店铺不存在");
        }
        
        // 3. 构建用户实体
        User user = new User();
        BeanUtils.copyProperties(request, user);
        user.setRole("manager");  // 设置为店长角色
        user.setStatus("active"); // 新创建的账户默认为激活状态
        user.setPassword(passwordEncoder.encode(request.getPassword())); // 密码加密
        
        // 4. 保存到数据库
        int result = userMapper.insert(user);
        if (result <= 0) {
            throw new RuntimeException("创建店长账户失败");
        }
        
        log.info("店长账户创建成功, userId: {}, username: {}, shopId: {}", 
                user.getId(), user.getUsername(), user.getShopId());
        
        // 5. 返回创建结果
        return convertToResponse(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ManagerResponse updateManager(ManagerUpdateRequest request) {
        log.info("超级管理员更新店长账户信息, managerId: {}", request.getId());
        
        // 1. 检查用户是否存在
        User existingUser = userMapper.selectById(request.getId());
        if (existingUser == null || !"manager".equals(existingUser.getRole())) {
            throw new RuntimeException("店长账户不存在");
        }
        
        // 2. 构建更新实体（只更新允许的字段）
        User updateUser = new User();
        updateUser.setId(request.getId());
        updateUser.setRealName(request.getRealName());
        updateUser.setPhone(request.getPhone());
        updateUser.setEmail(request.getEmail());
        
        // 3. 执行更新
        int result = userMapper.updateBasicInfo(updateUser);
        if (result <= 0) {
            throw new RuntimeException("更新店长账户信息失败");
        }
        
        log.info("店长账户信息更新成功, managerId: {}", request.getId());
        
        // 4. 返回更新后的信息
        return getManagerById(request.getId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateManagerStatus(Long id, String status) {
        log.info("超级管理员更新店长账户状态, managerId: {}, status: {}", id, status);
        
        // 1. 验证参数
        if (id == null || id <= 0) {
            throw new IllegalArgumentException("无效的用户ID");
        }
        
        if (!VALID_STATUSES.contains(status)) {
            throw new IllegalArgumentException("无效的账户状态: " + status);
        }
        
        // 2. 检查用户是否存在
        User existingUser = userMapper.selectById(id);
        if (existingUser == null || !"manager".equals(existingUser.getRole())) {
            throw new RuntimeException("店长账户不存在");
        }
        
        // 3. 更新状态
        int result = userMapper.updateStatus(id, status);
        if (result > 0) {
            log.info("店长账户状态更新成功, managerId: {}, oldStatus: {}, newStatus: {}", 
                    id, existingUser.getStatus(), status);
            return true;
        } else {
            log.error("店长账户状态更新失败, managerId: {}", id);
            return false;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean resetManagerPassword(Long id, String newPassword) {
        log.info("超级管理员重置店长密码, managerId: {}", id);
        
        // 1. 验证参数
        if (id == null || id <= 0) {
            throw new IllegalArgumentException("无效的用户ID");
        }
        
        if (newPassword == null || newPassword.trim().length() < 6) {
            throw new IllegalArgumentException("密码长度至少6位");
        }
        
        // 2. 检查用户是否存在
        User existingUser = userMapper.selectById(id);
        if (existingUser == null || !"manager".equals(existingUser.getRole())) {
            throw new RuntimeException("店长账户不存在");
        }
        
        // 3. 加密新密码并更新
        String encodedPassword = passwordEncoder.encode(newPassword.trim());
        int result = userMapper.updatePassword(id, encodedPassword);
        
        if (result > 0) {
            log.info("店长密码重置成功, managerId: {}", id);
            return true;
        } else {
            log.error("店长密码重置失败, managerId: {}", id);
            return false;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteManager(Long id) {
        log.warn("超级管理员删除店长账户, managerId: {}", id);
        
        // 1. 验证参数
        if (id == null || id <= 0) {
            throw new IllegalArgumentException("无效的用户ID");
        }
        
        // 2. 检查用户是否存在
        User existingUser = userMapper.selectById(id);
        if (existingUser == null || !"manager".equals(existingUser.getRole())) {
            throw new RuntimeException("店长账户不存在");
        }
        
        // 3. 执行删除（注意：这是系统级删除，会影响相关数据）
        int result = userMapper.deleteById(id);
        if (result > 0) {
            log.warn("店长账户删除成功, managerId: {}, username: {}", id, existingUser.getUsername());
            return true;
        } else {
            log.error("店长账户删除失败, managerId: {}", id);
            return false;
        }
    }

    @Override
    public boolean isUsernameExists(String username) {
        if (username == null || username.trim().isEmpty()) {
            return false;
        }
        return userMapper.countByUsername(username.trim()) > 0;
    }

    @Override
    public boolean isUsernameExists(String username, Long excludeId) {
        if (username == null || username.trim().isEmpty()) {
            return false;
        }
        if (excludeId == null || excludeId <= 0) {
            return isUsernameExists(username);
        }
        return userMapper.countByUsernameExcludeId(username.trim(), excludeId) > 0;
    }

    /**
     * 转换User实体为响应DTO
     */
    private ManagerResponse convertToResponse(User user) {
        if (user == null) {
            return null;
        }
        
        ManagerResponse response = new ManagerResponse();
        BeanUtils.copyProperties(user, response);
        
        // 设置店铺名称
        if (user.getShopId() != null) {
            Shop shop = shopMapper.selectById(user.getShopId());
            if (shop != null) {
                response.setShopName(shop.getName());
            }
        }
        
        return response;
    }
}